<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2-4-待办任务列表-组合式</title>
</head>

<body>


    <!--载入vue.js-->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <div id="Application">
        <!--输入框元素，用来新建待办任务-->
        <form @submit.prevent="addTask">
            <!--.prevent修改提交属性，使其提交不刷新页面-->
            <span>新建任务</span>
            <input v-model="taskText" placeholder="请输入任务..." />
            <button>添加</button>
        </form>

        <!--有序列表，使用v-for来构建-->
        <ol>
            <li v-for="item in todos" :key="keys">
                {{item}}
                <button @click="remove(keys)">
                    删除任务
                </button>
                <hr />
            </li>
        </ol>

    </div>



    <script>
        const app = Vue.createApp({
            setup() {
                //待办任务列表数据
                const todos = Vue.reactive([])

                //当前输入的待办任务
                const taskText = Vue.ref("")

                const keys = Vue.ref()

                //提交按钮
                const addTask = () => {
                    //判断输入框是否为空
                    if (taskText.value.length == 0) {
                        alert("请输入任务")
                        return;
                    }
                    todos.push(taskText.value)//给数组添加新元素
                    taskText.value = ""
                }

                //删除一条待办任务
                const remove = (keys) => {
                    todos.splice(keys, 1)
                }

                return {
                    taskText,
                    todos,
                    keys,
                    addTask,
                    remove,
                }
            }
        })

        app.mount("#Application")
    </script>

    <style>

    </style>


</body>

</html>